package com.imooc.ecommerce.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.ecommerce.kafka.KafkaProducer;
import com.imooc.ecommerce.vo.QinyiMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>SpringBoot 集成 kafka 发送消息
 *
 * @author Yaxi.Zhang
 * @since 2022/11/15 16:28
 */
@Slf4j
@RestController
@RequestMapping("/kafka")
public class KafkaController {
    private final ObjectMapper mapper;
    private final KafkaProducer kafkaProducer;
    private final AtomicInteger ai = new AtomicInteger(0);

    public KafkaController(ObjectMapper mapper, KafkaProducer kafkaProducer) {
        this.mapper = mapper;
        this.kafkaProducer = kafkaProducer;
    }

    /**
     * <p>发送 kafka 消息
     */
    @GetMapping("/send-message")
    public void sendMessage(@RequestParam(required = false) String key, @RequestParam String topic) throws Exception {
        Integer count = ai.incrementAndGet();
        QinyiMessage message = new QinyiMessage(count, "Imooc-Study-Ecommerce" + count);
        kafkaProducer.sendMessage(key, mapper.writeValueAsString(message), topic);
    }

}
